<?php
Yii::import('application.commands.tasks.*');

/**
 * 计划任务：处理器
 */
final class TaskRouter
{

	/**
	 * @return array 返回任务列表，以名称为键/中文描述为值
	 */
	public static function allTask()
	{
		$ret = array();
		$root = Yii::getPathOfAlias('application.commands.tasks');
		if (($dir = @dir($root)) !== false) {
			while (($entry = $dir->read()) !== false) {
				if (($pos = strrpos($entry, 'Task.php')) !== false) {
					$name = substr($entry, 0, $pos);
					$class = $name . 'Task';
					if (class_exists($class)) {
						$ret[$name] = call_user_func(array($class, 'label'));
					}
				}
			}
			$dir->close();
		}
		return $ret;
	}

	/**
	 * 执行计划任务	 
	 * @param Task $task 要执行的任务
	 */
	public static function runTask(Task $task)
	{
		$class = $task->name . 'Task';
		if (!class_exists($class)) {
			$task->status = 'failed';
			Yii::log('Skip unknown task [' . $task->name . '] ...', CLogger::LEVEL_WARNING);
		} else {
			$task->status = 'ongoing';
			$obj = new $class();
			Yii::log('Begin to run task [' . $task->name . '] ...');
			if ($obj->run($task) === true) {
				$task->status = 'finished';
				Yii::log('Finish the task [' . $task->name . ']');
			} else {
				$task->status = 'failed';
				Yii::log('Fail to finish the task [' . $task->name . ']');
			}
		}
	}
}

/**
 * 计划任务：类接口
 */
interface TaskInterface
{

	/**
	 * @return string 返回任务中文描述
	 */
	public static function label();

	/** 	 
	 * @param Task $task 任务数据模型
	 * @return boolean 任务执行结果，成功为 true 失败为 false
	 */
	public function run(Task $task);
}
